package gps.monitor.jt809server.protocol.codec;

import gps.monitor.jt809server.protocol.Jt809ParseException;
import gps.monitor.jt809server.protocol.model.AbstractJt809Message;
import gps.monitor.jt809server.protocol.model.Jt809UpExgMsgMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;

import java.nio.charset.Charset;

/**
 * @author cyq
 * @date 2021/11/7
 * @desc talk is cheep,show me the code
 */
public interface Jt809UpExgMsgHandler<T> extends IJt809SubHandler {

    /**
     * 读取子协议形式的body ，dataLenth 后面的部分
     * @param byteBuf
     * @return T
     * @throws Jt809ParseException
     */
    T readBody( ByteBuf byteBuf) throws Jt809ParseException;

    /**
     * 子协议的头部（假想）
     * @param upExgMsgMessage
     * @param byteBuf
     */
    default void readUpExgMsgHeader(Jt809UpExgMsgMessage upExgMsgMessage, ByteBuf byteBuf) {

        String vehicleNo = byteBuf.readBytes(21).toString(Charset.forName("GBK"));
        int enchar = vehicleNo.indexOf('\0');
        if (enchar >= 0) vehicleNo = vehicleNo.substring(0, enchar);
        byte vehicleColor = byteBuf.readByte();
        int dataType = Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(2)), 16);
        int dataLen = Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(4)), 16);

        upExgMsgMessage.setVehicleNo(vehicleNo);
        upExgMsgMessage.setVehicleColor(vehicleColor);
        upExgMsgMessage.setDataType(dataType);
        upExgMsgMessage.setDataLen(dataLen);
    }
}
